//
//  DZWeichatManager.m
//  WeichatLogin
//
//  Created by Darren on 15/6/2.
//  Copyright (c) 2015年 Darren Zheng. All rights reserved.
//

#import "DZWeichatManager.h"

@interface DZWeichatManager ()
@property (nonatomic, strong) NSString *strCode;
@property (nonatomic, strong) DZWeichatAuthModel *authModel;
@property (nonatomic, copy) void (^blockGotUserInfo)(DZWeichatUserInfoModel *userInfoModel);
@property (nonatomic, copy) void (^blockGotCode)(NSString *strCode);

@property (nonatomic, assign) BOOL bGetCodeOnly;
@end

@implementation DZWeichatManager

+ (DZWeichatManager *)sharedInstance
{
    static DZWeichatManager *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (void)registerWeichat
{
    [WXApi registerApp:WEICHAIT_APPID withDescription:@"weichat"];
}

- (void)getUserInfo:(void (^)(DZWeichatUserInfoModel *userInfoModel))completion
{
    self.bGetCodeOnly = NO;
    [self sendAuthRequest];
    self.blockGotUserInfo = completion;
}

- (void)getCode:(void (^)(NSString *strCode))completion
{
    self.bGetCodeOnly = YES;
    [self sendAuthRequest];
    self.blockGotCode = completion;
}

- (void)sendAuthRequest
{
    SendAuthReq* req =[[SendAuthReq alloc ] init];
    req.scope = @"snsapi_userinfo";
    [WXApi sendReq:req];
}

-(void)onResp:(BaseResp *)resp
{
    /*
     ErrCode ERR_OK = 0(用户同意)
     ERR_AUTH_DENIED = -4（用户拒绝授权）
     ERR_USER_CANCEL = -2（用户取消）
     code    用户换取access_token的code，仅在ErrCode为0时有效
     state   第三方程序发送时用来标识其请求的唯一性的标志，由第三方程序调用sendReq时传入，由微信终端回传，state字符串长度不能超过1K
     lang    微信客户端当前语言
     country 微信用户当前国家信息
     */
    
    if([resp isKindOfClass:[SendAuthResp class]])
    {
        SendAuthResp *aresp = (SendAuthResp *)resp;
        if (aresp.errCode== 0) {
            self.strCode = aresp.code;
            if (self.blockGotCode) {
                self.blockGotCode(aresp.code);
            }
            if (!self.bGetCodeOnly) {
                [self getAccessToken];
            }
        }
    }
    
    if([resp isKindOfClass:[PayResp class]]) {
        resp = (PayResp *)resp;
        
        NSString *code = [NSString stringWithFormat:@"%d", resp.errCode];
        
        NSLog(@"微信Code = %@",code);
        [[NSNotificationCenter defaultCenter] postNotificationName:@"WXPayResult" object:nil userInfo:@{@"payCode" : code}];
    }
    
    // 分享回调
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        NSString * message = nil;
        switch (resp.errCode) {
            case WXSuccess:
                message = @"分享成功！";
                [SVProgressHUD showSuccessWithStatus:message];
                   [[NSNotificationCenter defaultCenter]postNotificationName:@"sharepay" object:nil];
                break;
            case WXErrCodeCommon:
                message = @"分享失败，普通错误类型！";
                [SVProgressHUD showErrorWithStatus:message];
                
                break;
            case WXErrCodeUserCancel:
                message = @"你已经取消分享了！";
                [SVProgressHUD showErrorWithStatus:message];
                
                break;
            case WXErrCodeSentFail:
                message = @"分享失败，发送请求失败！";
                [SVProgressHUD showErrorWithStatus:message];
                
                break;
                
            case WXErrCodeAuthDeny:
                message = @"分享失败，授权失败！";
                [SVProgressHUD showErrorWithStatus:message];
                
                break;
            case WXErrCodeUnsupport:
                message = @"分享失败，微信不支持！";
                [SVProgressHUD showErrorWithStatus:message];
                
                break;
                
            default:
                break;
        }
        
        if (resp.errCode == WXSuccess)
        {
        }
        else
        {
        }
   
    }
}

-(void)getAccessToken
{
    if (!self.strCode) {
        return;
    }
    
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WEICHAIT_APPID,WEICHAIT_APPSECRET,self.strCode];
    
//    NSLog(@"微信url11111 = %@",url);
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data){
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                self.authModel = [DZWeichatAuthModel modelObjectWithDictionary:dic    ];
                
                [self getUserInfo];
            }
        });
    });
}

-(void)getUserInfo
{
    if (!self.authModel.accessToken || !self.authModel.openid) {
        return;
    }
    
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@", self.authModel.accessToken, self.authModel.openid];
//        NSLog(@"微信url222222 = %@",url);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                
                
//                 NSLog(@"微信url333333 = %@",dic);
                DZWeichatUserInfoModel *model = [DZWeichatUserInfoModel modelObjectWithDictionary:dic];
                if (self.blockGotUserInfo) {
                    self.blockGotUserInfo(model);
                }
            }
        });
    });
}

- (BOOL)bIsInstalled
{
    return [WXApi isWXAppInstalled];
}

@end
